<?php

namespace App\Http\Controllers;

use App\Models\Files;
use App\Models\Flows;
use App\Models\Lists;
use App\Models\messages;
use App\Models\Users;
use Illuminate\Http\Request;
use App\Http\Lib\ResBase;
use App\Http\Lib\Validator;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\Finder\SplFileInfo;
use function PHPUnit\Framework\isEmpty;

class FileController extends Controller
{
    public function upload(Request $request)
    {
        //判断文件格式，应该存入哪个文件夹
        $imgCollection = collect(['image/gif', 'image/jpeg', 'image/bmp','image/png','image/tiff','image/x-pict','image/x-photoshop','image/vnd.wap.wbmp']); // image 集合
        $pptCollection = collect(['application/vnd.ms-powerpoint ','application/vnd.openxmlformats-officedocument.presentationml.presentation','ssss','ssss','ssss','ssss']); // ppt 集合
        $wpsCollection = collect(['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/msword','application/x-mswrite','application/rtf','application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','text/css','text/html','text/plain','text/xml','text/wml','text/x-uuencode']); // wps 集合
        $videoCollection = collect(['video/x-msvideo','video/mpeg','video/quicktime','audio/wav','audio/mpeg','audio/mpeg']); // video 集合
        $pdfCollection = collect(['application/pdf']); // pdf 集合

        $list = $request->input('fileCate'); //所属文件夹id
        $uploader = $request->input('uploader');  //上传者
        $file = $request->file('file');
        $root = $request->input('root');  //权限
        //判断文件是否上传成功
        if ($file->isValid()){
            //原文件名
            $oName = $file->getClientOriginalName();
            $fileNameWithOutExt = pathinfo($oName, PATHINFO_FILENAME); //不带扩展名的文件名
            //扩展名
            $ext = $file->getClientOriginalExtension();
            //MimeType
            $type = $file->getClientMimeType();
            //临时绝对路径
            $realPath = $file->getRealPath();
            $filename = $fileNameWithOutExt.time().'.'.$ext;
            //判断文件类型和存储位置
            if ($imgCollection->contains($type)) {
                $diskType = 'img';
            } else if($pptCollection -> contains($type)){
                $diskType = 'ppt';
            } else if($wpsCollection -> contains($type)){
                $diskType = 'wps';
            } else if($videoCollection -> contains($type)){
                $diskType = 'video';
            }  else if($pdfCollection -> contains($type)){
                $diskType = 'pdf';
            } else {
                $diskType = 'oth';
            }
            // 存储文件，并获取存储的路径
            $storagePath = Storage::disk($diskType)->put($filename, file_get_contents($realPath));
            //返回的文件地址
            $filePath = Storage::disk($diskType)->path($filename);
            //查询是否有这个文件夹
            $isList = Lists::find($list);
            if(!$isList){
                return ResBase::ApiRes(404,'所选文件夹不存在','failed');
            }
//            var_dump($filename);
            //判断是否上传成功
            if($storagePath){
                try {
                    $res = Files::create([
                        'id' => Str::random(5),
                        'name' => $fileNameWithOutExt,
                        'belong_to' => $list,
                        'uploader' => $uploader,
                        'file' => $filePath,
                        'type' => $ext,
                        'mime'=> $type,
                        'root'=> $root,
                    ]);
                    if(!empty($res)){
                        $flow = Flows::create([
                            'name'=>$fileNameWithOutExt,
                            'status'=>0,
                            'initiator'=>Users::where('user_name',$uploader)->first()->user_id,
                            'file'=>$res->id,
                        ]);
                        if(!$flow){
                            return ResBase::ApiRes(402,$res,'创建流程失败');
                        } else {
                            //发通知
                            $msg = messages::create([
                                'name'=>$fileNameWithOutExt,
                                'content'=>'有新文件上传，请查看新文件',
                                'getter'=> 1,
                                'sender'=> Users::where('user_name',$uploader)->first()->user_id,
                                'type'=>'send'
                            ]);
                            if($msg){
                                return ResBase::ApiRes(200,'文件上传成功!');
                            } else {
                                return ResBase::ApiRes(403,'消息发送失败!');
                            }
                        }
                    } else {
                        return ResBase::ApiRes(401,$res,'上传创建失败');
                    }
                } catch (\Exception $e){
                    return ResBase::ApiRes(405,$e->getMessage(),'failed');
                }
            }else{
                return ResBase::ApiRes(400,'上传失败','failed');
            }
        }
    }
    //TODO:文件预览
    public function preview(Request $request){
        $fileId = $request->input('fileId');
        $file = Files::find($fileId);
        $filePath = $file->file;
        $mime = $file->mime;
        $name = $file->name;
        $ext = $file->type;
//        return $mime;
        return response()->file($filePath, ['Content-Type' => $mime]);
    }

    //TODO:文件下载
    public function download(Request $request){
        $fileId = $request->input('fileId');
        $file = Files::find($fileId);
        $filePath = $file->file;
        $name = $file->name;
        $ext = $file->type;
//        var_dump(file_exists($filePath));
        if(file_exists($filePath)){
            return response()->download($filePath,$name.'.'.$ext);
        } else {
            return ResBase::ApiRes(400,'文件不存在','failed');
        }
    }

    //获取文件列表
    public function getfiles(Request $request){
        $id = $request->input('listId');
        $userid = $request->input('userId');
        $c = Lists::find($id);
        $r = Users::where('user_id',$userid)->first();  //权限
        $root = $r->root;  //权限
        if(!$c){
            return ResBase::ApiRes(401,'目录不存在或已被删除','failed');
        }
        $res = Files::where('belong_to',$id)->where('root','>=',$root)->get();

        if($res && $res->count() > 0){
            return ResBase::ApiRes(200,$res);
        } else if ($res && $res->count() === 0) {
            return ResBase::ApiRes(201,'当前目录下没有文件','failed');
        } else {
            return ResBase::ApiRes(400,'获取失败','failed');
        }
    }

    //删除文件
    public function delfile(Request $request){
        $id = $request->input('fileId');
        $userid = $request->input('userId');
        $user = Users::where('user_id',$userid)->first();
        if($user->root>1){
            return ResBase::ApiRes(402,'当前用户没有权限删除文件','failed');
        }
        $res = Files::find($id);
        $path = $res->file;
        if($res){
            $r = File::delete($path);
            $d = $res->delete();
            if($d && $r){
                return ResBase::ApiRes(200,'删除成功');
            } else {
                return ResBase::ApiRes(400,'删除失败','failed');
            }
        } else {
            return ResBase::ApiRes(401,'目标文件不存在或已被删除','failed');
        }
    }

    //修改文件名
    public function updatefile(Request $request){
        $data = $request->all();
        $id = $data['fileId'];
        $name = $data['newFileName'];
        $userid = $request->input('userId');
        $user = Users::where('user_id',$userid)->first();
        if($user->root>2){
            return ResBase::ApiRes(403,'当前用户没有权限删除文件','failed');
        }
        $v = Validator::doValidator($data,['fileId'=>'required','newFileName'=>'required']);
        if($v){
            return ResBase::ApiRes(402,'参数缺失或错误','failed');
        }
        $res = Files::find($id);
        if(empty($res)){
            return ResBase::ApiRes(401,'目标文件不存在或已被删除','failed');
        }
        $cr = $res->update(['name'=>$name]);
        if(!$cr){
            return ResBase::ApiRes(400,'修改失败','failed');
        } else {
            return ResBase::ApiRes(200,'修改成功');
        }
    }
    //条件查询指定文件
    public function queryfile(Request $request){
        $key = $request->input('keyword');
        $v = Validator::doValidator($request->all(),['keyword'=>'required']);
        if($v){
            return ResBase::ApiRes(402,'参数错误或缺失','failed');
        }

//        $res = Files::where('name','like','%'.$key.'%')->get();
        $res = Files::where('name', 'like', "%$key%")->get();
        if(empty($res)){
            return ResBase::ApiRes(401,'没有符合条件的文件','failed');
        } else {
            $count = $res->count();
            return ResBase::ApiRes(200,['data'=>$res,'total'=>$count]);
        }
    }


}
